﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using SaiLing.Domain;
using SaiLing.Domain.Specification;
using SaiLing.Exceptions;
using SaiLing.Paging;
using SaiLing.SingleSignOn.Application.Service.Interfaces.System;
using SaiLing.SingleSignOn.Domain.Entities.System;
using SaiLing.SingleSignOn.Domain.Interfaces.System;
using SaiLing.SingleSignOn.Domain.Specifications.System;
using System.Linq;
using SaiLing.SingleSignOn.Domain.Entities.DataTransferObject;

namespace SaiLing.SingleSignOn.Application.Service.Providers.System
{
   public  class PositionService : BaseService<Position>, IPositionService
    {
        private IPositionRepository PositionRepository { get; set; }

        public PositionService(IUnitOfWork unitOfWork, IPositionRepository repository) : base(unitOfWork, repository)
        {
            PositionRepository = repository;
        }

        public Task<PageData<PositionDTO>> PageList(int pageIndex, int pageSize, string name)
        {
            var spec = new PositionSpecification(name);
            return PositionRepository.PageDataList(pageIndex, pageSize, spec, x => x.Sort, true);
        }

        public Task<IEnumerable<Position>> List(string name)
        {
            var spec = new PositionSpecification(name);
            return Task.FromResult(GetMany(spec));
        }

        public async Task<int> Create(Position entity)
        {
            if (await ExistsAsync(new DirectSpecification<Position>(x => x.FullName == entity.FullName && x.OrganizationId==entity.Id)))
                throw new SaiLingException("职位名称重复");
            await Add(entity);
            return await SaveChangesAsync();
        }

        public async Task<int> Edit(Position entity)
        {
            if (await ExistsAsync(new DirectSpecification<Position>(x => x.Id != entity.Id && x.FullName == entity.FullName && x.OrganizationId == entity.Id)))
                throw new SaiLingException("职位名称重复");
            Update(entity,
                x => x.FullName,
                x => x.OrganizationId,
                x => x.ShortName,
                x=>x.IsManage,
                x => x.Sort);
            return await SaveChangesAsync();
        }

        public async Task<int> Delete(Position[] entityies)
        {
            var ids = entityies.Select(x => x.Id).ToList();
            await LogicRemove(new DirectSpecification<Position>(x => ids.Contains(x.Id)));
            return await SaveChangesAsync();
        }
    }
}
